package com.cuit.service.impl;

import com.cuit.entity.ChartData;
import com.cuit.entity.Statistics;
import com.cuit.mapper.HomeMapper;
import com.cuit.service.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    private HomeMapper homeMapper;

    @Override
    public Statistics getStatistics(){
        Statistics statistics = new Statistics();
        statistics.setTotalUsers(homeMapper.countTotalUsers());
        statistics.setTotalVoices(homeMapper.countTotalVoices());
        statistics.setTodayVoices(homeMapper.countTodayVoices());
        Map<String, ChartData> chartDataMap = new HashMap<>();


        // 合并用户数据
        homeMapper.countDailyNewUsers().forEach(item -> {
            String date = (String) item.get("date");
            ChartData data = chartDataMap.computeIfAbsent(date, k -> new ChartData());
            data.setDate(date);
            data.setUserIndex(((Long) item.get("count")).intValue());
        });

        // 合并语音数据
        homeMapper.countDailyNewVoices().forEach(item -> {
            String date = (String) item.get("date");
            ChartData data = chartDataMap.computeIfAbsent(date, k -> new ChartData());
            data.setDate(date);
            data.setVoiceIndex(((Long) item.get("count")).intValue());
        });

        // 转换为有序列表
        List<ChartData> chartDataList = chartDataMap.values().stream()
                .sorted((a, b) -> a.getDate().compareTo(b.getDate()))
                .collect(Collectors.toList());

        statistics.setChartData(chartDataList);
        return statistics;
    }
}
